const http = require("http")
const until = require("./untils.js");
const { ObjectId } = require("mongodb");
var MongoClient = require("mongodb").MongoClient;
/* 如下
/api/articleList
/api/authorsList
/api/classifyArticleList
/api/findArticleDetails
/api/userLogin
/api/addUser
/api/myArticleList
/api/addArticle
/api/updateIdArticle
/api/deleteArticle
*/
var url = "mongodb://localhost:27017";
var db
MongoClient.connect(url, function (err, client) {
    if (err) throw err;
    db = client.db("lqsq");
});
const server = http.createServer((req, res) => {
    res.setHeader("content-type", "applaction/json;charset=utf-8")
    let path = req.url.split("?")[0]
    switch (path) {
        case "/api/articleList":
            db.collection("article").find().project({ _id: 1, title: 1, desc: 1, author: 1, authorId: 1, classify: 1, content: 1 }).toArray((err, resu) => {
                if (err) throw err
                until.infolog(path, JSON.stringify(resu))
                res.end(JSON.stringify(resu))
            });
            break
        case "/api/authorsList":
            //前提数据库中至少存在4条数据，否则将死循环
            db.collection("user").find().project({ _id: 1, userName: 1, headImg: 1, desc: 1 }).toArray((err, resu) => {
                if (err) throw err
                //使用set 存储不重复的数据取到随机的四个数据
                var four = new Set();
                while (four.size < 4) {
                    four.add(Math.floor(Math.random() * resu.length))
                }
                var arr = []
                four.forEach((e) => {
                    arr.push(resu[e])
                })
                var obj = {
                    "status": "ok",
                    "data": arr
                }
                until.infolog(path, JSON.stringify(obj))
                res.end(JSON.stringify(obj))
            });
            break
        case "/api/classifyArticleList":
            var classify = until.getparam(req.url,"classify")
            db.collection("article").find({ "classify": classify }).project({ _id: 1, title: 1, desc: 1, author: 1, authorId: 1, classify: 1, content: 1 }).toArray((err, resu) => {
                if (err) throw err
                until.infolog(path, JSON.stringify(resu))
                res.end(JSON.stringify(resu))
            });

            break
        case "/api/findArticleDetails":
            var id = until.getparam(req.url,"id")

            db.collection("article").find({ "_id": new ObjectId(id) }).project({ _id: 1, title: 1, desc: 1, author: 1, authorId: 1, classify: 1, content: 1,time: 1 }).toArray((err, resu) => {
                if (err) throw err
                until.infolog(path, JSON.stringify(resu))
                res.end(JSON.stringify(resu))
            });
            break
        case "/api/userLogin":
            //接收数据 的变量
            var chunk = ""
            //数据来到时，去接收
            req.on("data", (data) => {
                chunk += data.toString()
            })
            //数据接收完后的操作
            req.on("end", () => {
                var username = until.getparam(path+"?"+chunk, "userName")
                var password = until.getparam(path+"?"+chunk, "userPassword")
                db.collection("user").find({ "userName": username, "userPassword": password }).project({ _id: 1, userName: 1, headImg: 1 }).toArray((err, resu) => {
                    if (err) throw err
                    var obj = {
                        "status": "ok",
                        "data": resu[0]
                    }
                    res.end(JSON.stringify(obj))
                });
            })
            break
        case "/api/addUser":
            var chunk = ""

            req.on("data", (data) => {
                chunk += data.toString()
            })
            req.on("end", () => {
                var username = until.getparam(path+"?"+chunk, "userName")
                var password = until.getparam(path+"?"+chunk, "userPassword")
                var desc = until.getparam("?"+chunk, "desc")
                db.collection("user").find({ "userName": username }).project({ _id: 1, userName: 1, headImg: 1 }).toArray((err, resu) => {
                    if (err) throw err
                    //没有找到即存在 再进行添加用户
                    if (resu[0] == undefined) {
                        var createTime = new Date()
                        db.collection("user").insertOne({ "userName": username, "userPassword": password, "desc": desc, "headImg": "default.jpg", "createTime": createTime }, (err, resu) => {
                            if (err) throw err
                            let obj = {
                                "_id": resu.insertedId,
                                "userName": username,
                                "createTime": createTime,
                                "headImg": "default.jpg",
                                "desc": desc,
                            }
                            until.infolog(path, JSON.stringify(obj))
                            res.end(JSON.stringify(obj))
                        })
                    } else {
                        let obj = {
                            "status": "ok"
                        }
                        res.end(JSON.stringify(obj))
                    }
                });
            })
            break
        case "/api/myArticleList":
            var userId = until.getparam(req.url,"userId")

            db.collection("article").find({ "authorId": userId }).project({ _id: 1, title: 1, desc: 1, author: 1, authorId: 1, classify: 1, content: 1 }).toArray((err, resu) => {
                if (err) throw err
                until.infolog(path, JSON.stringify(resu))
                res.end(JSON.stringify(resu))
            });
            break
        case "/api/addArticle":
            var chunk = ""

            req.on("data", (data) => {
                chunk += data.toString()
            })
            req.on("end", () => {
                var title = until.getparam(path+"?"+chunk, "title")
                var content = until.getparam(path+"?"+chunk, "content")
                var desc = until.getparam(path+"?"+chunk, "desc")
                var author = until.getparam(path+"?"+chunk, "author")
                var authorId = until.getparam(path+"?"+chunk, "authorId")
                var classify = until.getparam(path+"?"+chunk, "classify")
                db.collection("article").insertOne({ "title": title, "content": content, "desc": desc, "author": author, "authorId": authorId, "classify": classify, "time": new Date() }, (err, resu) => {
                    if (err) throw err
                    let obj = `{${resu.acknowledged};}`
                    until.infolog(path, obj)
                    res.end(obj)
                })
            })

            break
        case "/api/updateIdArticle":
            var chunk = ""

            req.on("data", (data) => {
                chunk += data.toString()
            })
            req.on("end", () => {
                var _id = until.getparam(path+"?"+chunk, "_id")
                var title = until.getparam(path+"?"+chunk, "title")
                var content = until.getparam(path+"?"+chunk, "content")
                var desc = until.getparam(path+"?"+chunk, "desc")
                var author = until.getparam(path+"?"+chunk, "author")
                var authorId = until.getparam(path+"?"+chunk, "authorId")
                var classify = until.getparam(path+"?"+chunk, "classify")
                var time = new Date()
                db.collection("article").updateOne({ "_id": new ObjectId(_id) }, { $set: { "title": title, "content": content, "desc": desc, "author": author, "authorId": authorId, "classify": classify, "time": time } }, (err, resu) => {
                    if (err) throw err
                    let obj = {
                        "title": title,
                        "content": content,
                        "desc": desc,
                        "author": author,
                        "authorId": authorId,
                        "classify": classify,
                        "time": time,
                        "__v": 0,
                        "_id": _id
                    }
                    until.infolog(path, JSON.stringify(obj))
                    res.end(JSON.stringify(obj))
                })
            })

            break
        case "/api/deleteArticle":
            var id = until.getparam(req.url,"id")

            db.collection("article").deleteOne({ "_id": new ObjectId(id) }, (err, resu) => {
                if (err) throw err
                if (resu.deletedCount >= 1) {
                    let obj = `{${resu.acknowledged};}`
                    until.infolog(path, obj)
                    res.end(obj)
                } else {
                    let obj = `{false;}`
                    until.infolog(path, obj)
                    res.end(obj)
                }
            })
            break
        default :
            let obj = {
                errorinfo:"未知请求"
            }
            res.end(JSON.stringify(obj))
    }
})

server.listen(3001, () => {
    console.log("server start ...")
})